package com.ft.adbix.utils.data.gather.util.device;

import android.text.TextUtils;

import com.ft.adbix.utils.data.SPManager;
import com.ft.adbix.utils.data.synchronize.constant.SpConstant;

import java.io.RandomAccessFile;

/**
 * @author : ciba
 * @date : 2018/7/23
 * @description : 获取CPU信息工具类
 */

public class CpuUtil {

    private static int cpuCoreNum = 0;
    //cpu频率 平均值

    public static int getCpuNum() {
        try {
            cpuCoreNum = SPManager.getInstance().getInt(SpConstant.SP_CACHE_CPU_NUM, 0);
            if (cpuCoreNum == 0) {
                cpuCoreNum = Runtime.getRuntime().availableProcessors();
                SPManager.getInstance().putInt(SpConstant.SP_CACHE_CPU_NUM, cpuCoreNum);
            }
            return cpuCoreNum > 0 ? cpuCoreNum : 1;
        } catch (Exception e) {
            return 1;
        }
    }

    public static long getCpuFrequency() {
        long frequency = SPManager.getInstance().getLong(SpConstant.SP_CACHE_CPU_FREQUENCY, 0L);
        if (frequency == 0L) {
            if (cpuCoreNum == 0) {
                cpuCoreNum = getCpuNum();
            }
            try {
                long total = 0L;
                for (int i = 0; i < cpuCoreNum; i++) {
                    long max = readCpuFrequency("/sys/devices/system/cpu/cpu" + i + "/cpufreq/cpuinfo_min_freq");
                    long min = readCpuFrequency("/sys/devices/system/cpu/cpu" + i + "/cpufreq/cpuinfo_min_freq");
                    total += (max + min) / 2;
                }
                frequency = total / cpuCoreNum;
                SPManager.getInstance().putLong(SpConstant.SP_CACHE_CPU_FREQUENCY, frequency);
            } catch (Exception e) {
                return 0;
            }
        }
        return frequency;
    }

    private static long readCpuFrequency(String path) {
        try {
            RandomAccessFile file = new RandomAccessFile(path, "r");
            String content = file.readLine();
            file.close();

            if (TextUtils.isEmpty(content)) {
                return 0L;
            }

            return Long.parseLong(content.trim());

        } catch (Exception e) {
            return 0L;
        }
    }

}
